<template>
	<view class="homeindex" :style="'background-image: url(' + homeindex_bg+ ')'">
		<back class="back" :extraData="extraData"></back>

		<view class="tiptop" :style="{marginTop:customTop}">
			<music v-if="music_url" :music_url="music_url" class="left"></music>
			<view v-else class="left"></view>
			<view class="right" @click="tsfn1">提示
			</view>
		</view>
		<view class="title flexcenter" @click="goHome">
			<image :src="`${imgPath}/upload/we/turntable17/title.png`" alt="" class="titleimg"></image>
		</view>
		<!-- 模板1 -->
		<view class="full_w luckbox" :style="{backgroundImage: `${imgPath}/upload/we/turntable17/bottom_bg.png`}">
			<LuckyWheel class="luckbg" style="margin: auto" ref="myLucky" width="600rpx" height="600rpx"
				:prizes="prizes" :blocks="blocks" :buttons="buttons" :defaultConfig="defaultConfig"
				:defaultStyle="defaultStyle" @start="startCallback" @end="endCallback" />

			<!-- <img class="bottom_bg" src="@/assets/images/turntable17/bottom_bg.png" alt="" /> -->
		</view>
		<image style="width: 89vw;
    height: 225rpx;
    margin: -116rpx 0 0 5.5vw;" :src="`${imgPath}/upload/we/turntable17/bottom_bg.png`" alt="" class="bottom_bg">
		</image>
		<!-- <div class="flexcenter"><img src="@/assets/images/turntable2/dash.png" class="dashimg" alt=""></div> -->
		<view class="tipbottom">

			<view class="infodraw" @click="lwfn">
				<image :src="`${imgPath}/upload/we/turntable17/gift.png`"></image>
			</view>
			<view class="infocomplain c_fff f16" @click="tousufn">
				客服
			</view>

			<uni-popup class="help_popup" ref="turnPopup" type="center">
				<DrawSuccess v-if="type==1" :drawitem='drawitem' @close='closePop' />
				<DrawFail v-if="type==2" @close='closePop' />
				<DrawZf v-if="type==3" @close='closePop' />
				<DrawGg v-if="type==4" :advert='advert' @close='closePop' />
				<!-- 定时抽奖 -->
				<victorydelayed v-if="type==5" :code="code" @close='closePop' />
			</uni-popup>

		</view>
	</view>
</template>

<script>
	import music from '../music.vue'
	import DrawFail from '../type/DrawFail.vue'
	import DrawSuccess from '../type/DrawSuccess.vue'
	import DrawGg from '../type/DrawGg.vue'
	import DrawZf from '../type/DrawZf.vue'
	import victorydelayed from '../type/VictoryDelayed.vue'

	import LuckyWheel from '@/components/@lucky-canvas/uni/lucky-wheel' // 大转盘
	import back from '../back.vue' //顶部
	export default {
		props: ["extraData", "music_url", "is_subscribe"],

		//extraData 小程序跳转过来的得到的数据集
		//music_url 音乐地址
		//is_subscribe 是否订阅抽奖
		data() {
			return {

				subscribe: false,
				customTop: 0,
				navigationBarHeight: "",
				rewardedVideoAd: "",
				url: "",
				play: false,
				type: 1,
				show_reweima: false,
				disabled: false,
				drawitem: null, //中奖
				advert: null, //广告参数
				code: null,
				prizes: [],
				show: false,
				imgPath: uni.$http.baseUrl,
				homeindex_bg: `${uni.$http.baseUrl}/upload/we/turntable17/bg.png`,
				background: "",
				blocks: [{
					padding: "100rpx",
					imgs: [{

						src: `${uni.$http.baseUrl}/upload/we/turntable17/turnimg.png`,
						width: "100%",
						rotate: true,
					}, ],
				}, ],

				// prizes: [
				// { fonts: [{ text: "谢谢参与",top:'1.5rem' }], imgs:[{src:require('@/assets/images/xxcy.png'),width:'1rem',height:'1rem',top:'12px'}] },
				// { fonts: [{ text: "二等奖",top:'1.4rem' }], imgs:[{src:require('@/assets/1.png'),width:'1rem',height:'1rem',top:'10px'}] },
				// { fonts: [{ text: "三等奖",top:'1.4rem' }], imgs:[{src:require('@/assets/1.png'),width:'1rem',height:'1rem',top:'10px'}] },
				// { fonts: [{ text: "3",top:'1.4rem' }], imgs:[{src:require('@/assets/1.png'),width:'1rem',height:'1rem',top:'10px'}] },
				// { fonts: [{ text: "4",top:'1.4rem' }], imgs:[{src:require('@/assets/1.png'),width:'1rem',height:'1rem',top:'10px'}] },
				// { fonts: [{ text: "5",top:'1.4rem' }], imgs:[{src:require('@/assets/1.png'),width:'1rem',height:'1rem',top:'10px'}] },
				// ],
				buttons: [{
						radius: "15%",
						background: "#617df2"
					},
					{
						radius: "10%",
						background: "#afc8ff"
					},
					{
						imgs: [{
							src: `${uni.$http.baseUrl}/upload/we/turntable17/btn.png`,
							top: "-80rpx",
							width: "140rpx",
							//   height: "6rem",
						}, ],
					},
				],
				// 默认配置
				defaultConfig: {
					// gutter: "2px",
				},
				defaultStyle: {
					// background: "#FFFBD5",
					fontSize: "30rpx",
					fontColor: "#000",
					lineClamp: 1,
				},
			};
		},
		components: {
			music,
			LuckyWheel,
			DrawFail,
			DrawSuccess,
			DrawGg,
			DrawZf,
			victorydelayed,
			back
		},
		created() {

		},
		mounted() {
			console.log("mountedmountedmounted")
			//this.url = uni.getStorageSync('url', 'session');
			this.customTop = (Number(uni.getStorageSync('customTop', 'session')) + 10) + "px";

			console.log("customTop", this.customTop)
		},
		onLoad() {

			// 创建激励视频广告实例
			this.rewardedVideoAd = uni.createRewardedVideoAd({
				adUnitId: 'adunit-54c4a06c561e267f' // 替换为你的激励视频广告位ID
			})

			// 监听激励视频广告加载成功事件
			this.rewardedVideoAd.onLoad(() => {
				this.rewardedVideoAd.show()
					.then(() => console.log('激励视频广告显示成功'))
					.catch(err => console.error('激励视频广告显示失败', err))
				console.log('激励视频广告加载成功')
			})

			// 监听激励视频广告关闭事件
			this.rewardedVideoAd.onClose((res) => {
				if (res.isEnded) {
					// 用户观看完整广告
					console.log('用户观看完整广告')
				} else {
					// 用户未观看完整广告
					console.log('用户未观看完整广告')
				}
			})

			// 监听激励视频广告错误事件
			this.rewardedVideoAd.onError((err) => {
				console.log('激励视频广告错误', err)
			})
		},
		created() {
			// 微信跳h5我的奖品
			// if(localStorage.getItem("information")==1){
			//   this.tsfn1()
			// }
			// if(this.$store.getters.information){
			//   let task = JSON.parse(sessionStorage.getItem("taskInfo")).task;
			//   this.$router.push("/information?id=" + task.id);
			// }
			this.setDraw();
		},
		methods: {

			closePop() {
				this.$refs.turnPopup.close()
			},
			startCallback() {

				if (this.is_subscribe) {
					this.requestSubscribe();
					return
				}

				// 正式0YqSvizy6GzDAnq97DYeNlrJqmahF_KWiP-MPlbdLEk
				//测试SxWYYWTKnxnfgxJA4hnl80iadiC4nx8DtGRCqM59WlU
				var templateId = "SxWYYWTKnxnfgxJA4hnl80iadiC4nx8DtGRCqM59WlU";
				var _this = this;
				let task = JSON.parse(uni.getStorageSync('taskInfo', 'session')).task;
				uni.requestSubscribeMessage({
					tmplIds: [templateId], // 需要订阅的模板ID
					success(res) {

						if (res[templateId] === 'accept') {
							var url1 = "/user/wechat/wxRemind?task_id=" + task.id;
							uni.$http.get(url1).then((res) => {
								res = res.data;
								_this.$emit('handleSubscribe', true);
								//_this.is_subscribe = true;
								_this.requestSubscribe() //请求接口抽奖
							});

						} else {
							console.log("用户拒绝了订阅")
							var url2 = "/user/wechat/wxRemindCancel?task_id=" + task.id;
							uni.$http.get(url2).then((res) => {
								res = res.data;
								_this.$emit('handleSubscribe', false);
								//_this.is_subscribe = false;
								_this.requestSubscribe() //请求接口抽奖
							});


						}
						// 用户允许订阅通知
					},
					fail(err) {
						// 用户拒绝授权或其他错误
						console.error(err);

						// 引导用户前往【设置】页面打开【接受订阅消息】权限

					}
				});
			},
			async requestSubscribe() {
				console.log('开始点击turnPopup')
				if (this.disabled) {
					uni.showToast({
						title: this.title,
						icon: "error"
					})
					return
				}
				// 调用抽奖组件的play方法开始游戏
				console.log('this.$refs.myLucky:', this.$refs.myLucky)
				this.$refs.myLucky.play();

				// 模拟调用接口异步抽奖
				let task = JSON.parse(uni.getStorageSync('taskInfo', 'session')).task;
				try {
					// let res = await getDraw({
					// 	id: task.id
					// })
					var res = await uni.$http.post("/wxuser/draw/run", { //调用抽奖
						id: task.id
					})
					res = res.data
					if (res.code == 0) {
						this.title = res.msg;
						uni.showToast({
							title: res.msg,
							icon: "error"
						})
						this.disabled = true;
						this.$refs.myLucky.init();
						return
					}
					let data = res.data,
						index = 0
					if (data.type) {
						this.type = data.type
						this.advert = data.advert
					} else {
						if (data.list) {
							if (data.list.code) {
								this.type = 5
								this.code = data.list.code
							} else {
								this.type = 1
								if (data.list.level || data.list.level == 0) {
									index = data.list.level
								} else {
									index = this.prizes.length - 1
								}
							}
							this.drawitem = data.list
						} else {
							this.type = 2
						}

					}
					console.log('测试：', this.type)
					setTimeout(() => {
						// 假设后端返回的中奖索引是0
						// const index = 0;
						// 调用stop停止旋转并传递中奖索引
						this.$refs.myLucky.stop(index)
					}, 3000);
				} catch (error) {
					console.log('测试测')
					setTimeout(() => {
						// 回到初始状态
						this.$refs.myLucky.init();
					}, 3000);
				}
			},

			endCallback(prize) {
				console.log(prize);
				if (JSON.stringify(prize) !== '{}') {
					this.$refs.turnPopup.open()
					this.show = true
				}
			},
			goHome() {
				uni.switchTab({
					url: '/pages/home/home'
				});

			},
			tousufn() {
				wx.openCustomerServiceChat({ //跳转到企业微信客服
					extInfo: {
						url: 'https://work.weixin.qq.com/kfid/kfc49fd496002f64760'
					},
					corpId: 'ww26c801ce25ace1c6',
					success(res) {

					},
					fail(res) {

					},
				})
			},
			lwfn() { //跳转到活动信息
				let task = JSON.parse(uni.getStorageSync('taskInfo', 'session')).task;
				let url = '/pagesPrize/aboutPrize/information?id=' + task.id + '&index=1'
				uni.navigateTo({
					url
				})
			},
			tsfn1() { //跳转到活动信息

				let task = JSON.parse(uni.getStorageSync('taskInfo', 'session')).task;
				let url = "/pagesPrize/aboutPrize/information?id=" + task.id
				uni.navigateTo({
					url
				})

			},
			// commsetting() {
			//   let setting = JSON.parse(sessionStorage.getItem("taskInfo")).setting;
			//   if (setting.bg_url) {
			//     this.background = this.domain + setting.bg_url;
			//   }
			//   if (setting.biaoti_url) {
			//     this.titltbg = this.domain + setting.biaoti_url;
			//   }
			// },
			// 设置奖项
			setDraw() {
				let info = JSON.parse(uni.getStorageSync('taskInfo', 'session'));

				let draw = info.draw;
				let draws = [{
					background: '#FF8400',
					fonts: [{
						text: "谢谢参与",
						top: "90rpx"
					}],
					imgs: [{
						src: `${uni.$http.baseUrl}/upload/we/turntable17/xxcy.png`,
						width: "80rpx",
						height: "80rpx",
						top: "12rpx",
					}, ],
					level: 0,
				}, ];
				draw.forEach((item, index) => {
					let params = {
						background: index % 2 == 0 ? '#FED893' : '#FF8400',
						fonts: [{
							text: item.draw_name,
							top: "90rpx"
						}],
						imgs: [],
						...item,
					};
					if (item.photo) {
						let imgparams = {
							width: "80rpx",
							height: "80rpx",
							top: "12rpx"
						};
						imgparams.src = `${uni.$http.baseUrl}/${item.photo}`;
						params.imgs.push(imgparams);
						params.fonts[0].top = "90rpx";
					}
					draws.push(params);
				});
				// 安慰奖
				if (info.comfort.status == 1) {
					let params = {
						background: draws.length % 2 == 0 ? '#FED893' : '#FF8400',
						fonts: [{
							text: info.comfort.draw_name,
							top: "22rpx"
						}],
						imgs: [],
						...info.comfort,
					};
					if (info.comfort.photo) {
						let imgparams = {
							width: "100rpx",
							height: "100rpx",
							top: "22rpx"
						};
						imgparams.src = `${uni.$http.baseUrl}/info.comfort.photo`;
						params.imgs.push(imgparams);
						params.fonts[0].top = "22rpx";
					}
					draws.push(params);
				}
				this.prizes = draws;
				console.log("prize:", this.prizes);
			},


		},
	};
</script>

<style lang="scss" scoped>
	.homeindex {
		width: 100vw;
		height: 94vh;

		overflow: hidden;
		background-repeat: no-repeat;
		background-size: cover;

		.back {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
		}

		.popup_erweima_box {
			width: 300rpx;
			height: 300rpx;

			.box1 {
				width: 100%;
				height: 100%;
			}
		}

	}

	.title {
		margin-top: 20rpx;
		height: 160rpx;
		margin-bottom: 20rpx;
	}

	.titleimg {
		width: 80%;
		max-height: 150rpx;
	}

	.luckbox {
		height: 660rpx;
		//overflow: hidden;
		position: relative;
		background-size: contain;
		/* 控制背景图像的大小，使其完全包含在元素内 */
		background-position: center bottom;
		/* 将背景图像在元素的底部居中 */
		background-repeat: no-repeat;

		/* 防止背景图像重复 */
		.bottom_bg {
			// position: absolute;
			// //bottom: 0;
			// top: 360rpx;
			// z-index: 0;
			// left: 1%;
			// transform: translate(0, -1%);
			width: 98%;
		}

		.bottom_bg {
			width: 98vw;
			height: 60rpx;
		}
	}

	.luckbg {
		// background-color: #e52037;
		border-radius: 100%;
		overflow: visible !important;
		z-index: 1;
		position: relative;
	}

	.popupbg {
		width: 100%;
		background-color: transparent;
	}

	.tiptop {
		display: flex;
		margin: 150rpx 0rpx 0 20rpx;
		justify-content: space-between;
		color: #fff;


		.right {
			background: #911100;
			border-radius: 40rpx 0 0 40rpx;
			width: 160rpx;
			height: 60rpx;
			border-right: 0;
			line-height: 60rpx;
			color: #FED11A;
			text-align: center;
			font-size: 28rpx;
		}

	}

	.tipbtn {
		width: 1.81rem;
		height: 0.75rem;
		background: #911100;
		border-radius: 0.33rem 0px 0px 0.33rem;
		width: 1.81rem;
		height: 0.75rem;
		// border: 2px solid #000000;
		border-right: 0;
		line-height: 0.75rem;

		color: #FED11A;
	}

	.po_bottom {
		position: absolute;
		right: 0.534rem;
		bottom: 1.1rem;
	}

	.gift {
		width: 1.386rem;
		height: 1.386rem;
		margin-bottom: 30px;
	}

	.tips2 {
		width: 0.85rem;
		height: 0.85rem;
	}

	.infodraw {
		position: absolute;
		right: 20rpx;
		bottom: 100rpx;
		width: 100rpx;
		height: 100rpx;

		image {
			width: 80rpx;
			height: 80rpx;
		}
	}

	.infocomplain {
		position: absolute;
		left: 0.267rem;
		bottom: 130rpx;
		color: #000;
	}

	.dashimg {
		height: 180px;
		margin-top: -70px;
	}

	@keyframes music {
		from {
			transform: rotate(0);
		}

		to {
			transform: rotate(360deg);
		}
	}
</style>